package tree.leetcode_103_medium;

import java.util.*;

//双栈交替法
public class ZigzagLevelOrder {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> lists = new ArrayList<>();
        if (root == null) {
            return lists;
        }
        //stack1存奇数层，奇数层的输出顺序是：从左到右，所以存储顺序是：从右到左
        Stack<TreeNode> stack1 = new Stack<>();
        //stack2存偶数层，奇数层的输出顺序是：从右到左，所以存储顺序是：从左到右
        Stack<TreeNode> stack2 = new Stack<>();
        //根节点在第一层
        stack1.push(root);
        //两个栈都空，循环结束
        while (!stack1.isEmpty() || !stack2.isEmpty()) {
            List<Integer> temp = new ArrayList<>();
            TreeNode cur = null;
            if (!stack1.isEmpty()) {
                while (!stack1.isEmpty()) {
                    cur = stack1.pop();
                    temp.add(cur.val);
                    //此时用stack2存下一层
                    if (cur.left != null) {
                        stack2.push(cur.left);
                    }
                    if (cur.right != null) {
                        stack2.push(cur.right);
                    }
                }
                lists.add(temp);
            } else {  //stack1空
                while (!stack2.isEmpty()) {
                    cur = stack2.pop();
                    temp.add(cur.val);

                    if (cur.right != null) {
                        stack1.push(cur.right);
                    }
                    if (cur.left != null) {
                        stack1.push(cur.left);
                    }
                }
                lists.add(temp);
            }
        }
        return lists;
    }
}
